﻿package idv.cjcat.emitter.behaviors {
	use namespace engine;
	
	import idv.cjcat.emitter.*;
	import idv.cjcat.emitter.ds.*;
	
	/**
	 * Spawn behavior.
	 */
	public class SpawnBehavior extends Behavior {
		
		/**
		 * The spawned particle.
		 */
		public var particle:Particle;
		/**
		 * Spawn count.
		 */
		public var amount:Number;
		public var amountVar:Number;
		/**
		 * Whether the spawned particles inherit their ancestors' velocities.
		 */
		public var inheritDirection:Boolean = true;
		
		public function SpawnBehavior(particle:Particle = null, amount:Number = 3, amountVar:Number = 0) {
			this.particle = particle;
			this.amount = amount;
			this.amountVar = amountVar;
		}
		
		override public function behave(pd:ParticleData):void {
			if (particle == null) return;
			
			var s:PointSource = PointSourcePool.get();
			if (inheritDirection) {
				particle.direction.x = pd.vx;
				particle.direction.y = pd.vy;
				
				//fix zero-length direction problem
				if (particle.direction.length == 0) {
					particle.direction.x = pd.particleClass.direction.x;
					particle.direction.y = pd.particleClass.direction.y;
				}
			}
			s.addParticle(particle);
			s.active = false;
			s.x = pd.cx;
			s.y = pd.cy;
			
			s.burst(EmitterMath.uniformSample(amount, amountVar));
			s.spawn(pd.emitter);
			s.clearParticles();
			PointSourcePool.recycle(s);
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = BehaviorType.SPAWN;
			xml.@amount = amount.toString();
			xml.@amountVar = amountVar.toString();
			xml.@inheritDirection = inheritDirection.toString();
			xml.@particle = (particle != null)?(particle._id):("null");
			
			return xml;
		}
		
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			
			amount = parseFloat(xml.@amount);
			amountVar = parseFloat(xml.@amountVar);
			inheritDirection = (xml.@inheritDirection == "true");
			particle = EmitterGlobal.getParticleByID(xml.@particle);
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}